
   function initJqgrid(){
	   //$("#list1").tableDnD({scrollAmount:0});
	   initAddUserDialog();
	   initAddUserProductDialog();
	   initUserTypeAutocomplete();
$("#User_list1").jqGrid({
   	url:'../userHandle/editUser.jsp',
	datatype: "xml",
   	colNames:['用户(联系人)','用户名称','用户单位','用户密码','用户类型','业务员', '最后拜访时间', '地址','手机号码','删除'],
   	colModel:[
		{name:'User_ID',index:'User_ID', width:75},
   		{name:'User_Name',index:'User_Name', width:75,hidden:true },
		{name:'Login_Name',index:'Login_Name', width:75,editable:true},
		{name:'Login_Pwd',index:'Login_Pwd', width:75,editable:true},
   		{name:'User_Type',index:'User_type', width:50,edittype:'select',align:"center", formatter:'select', editoptions:{value:"1:管理员;2:业务员;3:客户;4:送货员"},},
		{name:'UP_ID',index:'UP_ID', width:75},
   		{name:'Called_Time',index:'Called_Time',width:100 ,align:"center"},
   		{name:'Addr',index:'Addr', width:80,editable:true, align:"left"},
   		{name:'Tel',index:'Tel', width:80,editable:true, align:"left"},	
		{name:'del',index:'del', width:80,formatter:FmatterDel,align:"center"},
   	],
	//scroll: true,
   	rowNum:10,
	scrollrows : true,
   	autowidth: true,
	height:400,
   	rowList:[10,20,30],
	prmNames:{page:'page',rows:'rows',order: 'sord', search:'_search', nd:'nd', npage:null},
	//postData:{page:'page',rows:'rows', sort: 'sidx',order: 'sordsdf'},
   	pager: jQuery('#User_pager1'),
   	sortname: 'User_ID',
    viewrecords: true,
    sortorder: "desc",
    caption:"XML Example",	
	forceFit : false,
	cellEdit: true,
	cellsubmit: 'clientArray',
	subGrid : true,
     subGridRowExpanded: function (subgrid_id, row_id){SubGrid(subgrid_id, row_id) },
	afterEditCell: function (id,name,val,iRow,iCol){
	
	
			
		
	},
	afterSaveCell : function(rowid,name,val,iRow,iCol) {
		var myrow = jQuery('#User_list1').jqGrid('getRowData',rowid);
		if(name!='User_ID'){
			ModifyUser(myrow.User_ID,name+"="+val);
			}
		
	},
	loadCompele:function(){alert("compele")},
	loadError:function(){alert("error")},
	onSelectRow: function(id){    


   },   
	gridComplete: function() {
    	$("#_empty","#list1").addClass("nodrag nodrop");
    }, 
	//此事件在点击表格特定单元格时发生。rowid 为行ID；iCol 为列索引；cellcontent 为单元格中内容；e 点击事件对象
	onCellSelect:function(rowid,iCol,cellcontent,e){
		if(iCol==10){
			var myrow = jQuery('#User_list1').jqGrid('getRowData',rowid);
			var aa= window.confirm("是否删除用户 '"+myrow.User_ID+"' (这将删除用户对应所有数据)！");
			if (aa) {
			
			delUser(myrow.User_ID);
			}
			}
		},
	editurl:"../userHandle/editUser.jsp",
	caption: "Input Types"
}).navGrid('#User_pager1',{edit:false,add:false,del:false,search: false }).navButtonAdd('#User_pager1',{   
   caption:"添加",    
   buttonicon:"ui-icon-add",    
   onClickButton: function(){    
    $('#User-form').dialog('open').children('form')[0].reset();  
   },    

   position:"last"  
}).navSeparatorAdd("#User_pager1",{sepclass : "ui-separator",sepcontent: ''});	
//jQuery("#list1").jqGrid('inlineNav',"#pager1");
	   }
	
		   //订单表格的二级表格初始化用户获取用户的产品价格
	   function SubGrid(subgrid_id, row_id){    
	  var User_ID=getUser_ID_By_Row(row_id);
	  //alert("subgrid_id="+subgrid_id+" row_id="+row_id+" Order_ID="+Order_ID);
         var subgrid_table_id; 
		 pager_id = "p_"+subgrid_table_id;
         jQuery("#"+subgrid_id).html("<table id='" + subgrid_table_id + "' class='scroll'></table><div id='"+pager_id+"' class='scroll'></div>"); 
         jQuery("#"+subgrid_table_id).jqGrid({      
            url: '../UserProductHandle/queryUserProduct.jsp', //获取数据
            datatype: "xml", 
			viewrecords: true,
			pager:jQuery("#"+pager_id),
            mtype: 'POST',
			cellsubmit: 'clientArray',
            colNames: ['ID','用户','产品名称','产品ID','优惠价格','添加时间','备注','删除'], 
            colModel: [ 
             {name:"ID", width:100,sortable:false,hidden:true}, 
             {name:"User_ID",width:75, sortable:false}, 
			 {name:"Product_Name",width:80,align:"left", sortable:false}, 
             {name:"Product_ID",width:80,align:"left",hidden:true, sortable:false}, 
             {name:"Price",width:80,editable:true,align:"left",sortable:false},
			 {name:"Add_Time",width:150,align:"center"} ,
			 {name:"Info",width:180,editable:true,align:"left",sortable:false,}, 
			 {name:'del',index:'del', width:50,formatter:FmatterDel,align:"center"},
              ], 
			postData:{page:'page',rows:'rows',order: 'sord', search:'_search', nd:'nd', npage:null,User_ID:encodeURIComponent(User_ID)},
            rowNum: 10, 
            imgpath: 'images图片URL', 
            sortname: 'Order_Products', 
			forceFit : true,
			cellEdit: true,
			afterEditCell: function (id,name,val,iRow,iCol){
			//alert(id+name+val+iRow+iCol);
			//$(this).jqGrid('saveRow',id);      
			},
			onCellSelect:function(rowid,iCol,cellcontent,e){
		if(iCol==7){
			var aa= window.confirm("是否删除用户产品价格信息！");
			if (aa) {
			var myrow = jQuery(this).jqGrid('getRowData',rowid);
			delUser_Product(myrow.User_ID,myrow.Product_ID,this);
			}
			}
		},
			afterSaveCell:function(rowid,name,val,iRow,iCol) {
				var myrow = $(this).jqGrid('getRowData',rowid);
			ModifyUserProduct(myrow.User_ID,myrow.Product_ID,name+"="+val);
			},
			editurl:"../userHandle/editUser.jsp",
            sortorder: "asc" }).navGrid("#"+pager_id,{edit:false,add:false,del:false,search: false }).navButtonAdd("#"+pager_id,{
   caption:"添加",    
   buttonicon:"ui-icon-add",    
   onClickButton: function(){    
   
	  var id = jQuery("#User_list1").jqGrid('getGridParam','selrow');   
	  if (id) {   
	  var ret = jQuery("#User_list1").jqGrid('getRowData',id);  
	   $('#UserProduct-form').dialog('open').children('form')[0].reset();  
	   $('#Add_UserProduct_UserID').val(ret.User_ID);  
	  } else {
		  alert("请选择这个用户！");
		  }
    
   },    
   position:"last"  
});
		   }
		   
//修改用户信息
function ModifyUser(User_ID,url){
		$.ajax({
   type: "POST",
   async: false,
   dataType: "xml",
   url: "../userHandle/editUser.jsp?oper=edit",
   data: encodeURI("User_ID="+User_ID+"&"+url),
   success: function(xmlResponse){
    //getStart(xmlResponse);
	var statuc=$(xmlResponse).find("statuc").text();	
	if(statuc=="true"){
		$("#User_list1").trigger("reloadGrid");
		Toalert($(xmlResponse).find('msg').text());
		
		}else{
		Toalert($(xmlResponse).find('msg').text());
		}
 	},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
                        alert("status:"+XMLHttpRequest.status+"readyState:"+XMLHttpRequest.readyState+"text:"+textStatus);
                    },
 });
	}
	
	function ModifyUserProduct(User_ID,Product_ID,url){
		$.ajax({
   type: "POST",
   async: false,
   dataType: "xml",
   url: "../UserProductHandle/editUserProduct.jsp?oper=edit",
   data: encodeURI("User_ID="+User_ID+"&"+"Product_ID="+Product_ID+"&"+url),
   success: function(xmlResponse){
    //getStart(xmlResponse);
	var statuc=$(xmlResponse).find("statuc").text();	
	if(statuc=="true"){
		Toalert($(xmlResponse).find('msg').text());
		//$("#User_list1").trigger("reloadGrid");
		}else{
		Toalert($(xmlResponse).find('msg').text());
		}
 	},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
                        alert("status:"+XMLHttpRequest.status+"readyState:"+XMLHttpRequest.readyState+"text:"+textStatus);
                    },
 });
	}
		  //通过订单表的行ID获取订单ID
	   function getUser_ID_By_Row(rowid){
		   var myrow = jQuery('#User_list1').jqGrid('getRowData',rowid);
			return myrow.User_ID;
		   }  
		   
	function FmatterUserType(cellvalue, options, rowObject){
		  if(cellvalue=='1'){
			  return "管理员";
		  }else if(cellvalue=='2'){
			  return "业务员";
		  }else if(cellvalue=='3'){
			  return "客户";
		  }else if(cellvalue=='4'){
			  return "送货员";
		  }
		}
	function FmatterDel(cellvalue, options, rowObject){
			return "删除";
		}
		
	function delUser(User_ID){
		$.ajax({
   type: "POST",
   async: false,
   dataType: "xml",
   url: "../userHandle/delectUser.jsp",
   data: encodeURI("User_ID="+User_ID),
   success: function(xmlResponse){
    //getStart(xmlResponse);
	var statuc=$(xmlResponse).find("statuc").text();	
	if(statuc=="true"){
		Toalert($(xmlResponse).find('msg').text());
		$("#User_list1").trigger("reloadGrid");
		}else{
		Toalert($(xmlResponse).find('msg').text());
		}
 	},
	error: function(XMLHttpRequest, textStatus, errorThrown) {
                        alert("status:"+XMLHttpRequest.status+"readyState:"+XMLHttpRequest.readyState+"text:"+textStatus);
                    },
 });
		}
		
	function delUser_Product(User_ID,Product_ID,jqgrid){
				$.ajax({
   type: "POST",
   async: false,
   dataType: "xml",
   url: "../UserProductHandle/delectUserProduct.jsp",
   data: encodeURI("User_ID="+User_ID+"&Product_ID="+Product_ID),
   success: function(xmlResponse){
    //getStart(xmlResponse);
	var statuc=$(xmlResponse).find("statuc").text();	
	if(statuc=="true"){
		Toalert($(xmlResponse).find('msg').text());
		$(jqgrid).trigger("reloadGrid");
		}else{
		Toalert($(xmlResponse).find('msg').text());
		}
 	},
	error: function(XMLHttpRequest, textStatus, errorThrown) {
                        alert("status:"+XMLHttpRequest.status+"readyState:"+XMLHttpRequest.readyState+"text:"+textStatus);
    },
 });
		}
  function addUser(User_ID,User_Name,Login_Name,User_Pwd,User_Type,UP_ID,Addr,Tel){
	  
	  var bValid = true;
					//allFields.removeClass( "ui-state-error" );
					bValid = bValid && checkLength($("#Add_User_ID"), "用户名", 1, 50 );
					bValid = bValid && checkLength($("#Add_User_Tel"), "手机号码", 11, 11 );
					bValid = bValid && checkLength($( "#Add_User_Pwd"), "密码", 5, 16 );
					//bValid = bValid && checkRegexp($("#Add_User_ID"), /^[a-z]([0-9a-z_])+$/, "用户名必须字母开头包括 a-z, 0-9,下划线 且长度3-16." );
					// From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
					
					bValid = bValid && checkRegexp($( "#Add_User_Pwd"), /^([0-9a-zA-Z])+$/, "密码只允许为 : a-z 0-9 长度5-16" );
					
					bValid = bValid && checkRegexp($( "#Add_User_Tel"), /^([0-9])+$/, "请输入正确手机号码" );
					
if(bValid){
	  	$.ajax({
   type: "POST",
   async: false,
   dataType: "xml",
   url: "../userHandle/addUser.jsp",
   data: encodeURI("User_ID="+User_ID+"&User_Name="+User_Name+"&Login_Name="+Login_Name+"&User_Pwd="+User_Pwd+"&User_Type="+User_Type+"&UP_ID="+UP_ID+"&Addr="+Addr+"&Tel="+Tel),
   success: function(xmlResponse){
    //getStart(xmlResponse);
	var statuc=$(xmlResponse).find("statuc").text();	
	if(statuc=="true"){
		$("#User_list1").trigger("reloadGrid");
		AddUserMsg($(xmlResponse).find('msg').text());
		
		}else{
		AddUserMsg($(xmlResponse).find('msg').text());
		}
 	},
	error: function(XMLHttpRequest, textStatus, errorThrown) {
                        alert("status:"+XMLHttpRequest.status+"readyState:"+XMLHttpRequest.readyState+"text:"+textStatus);
                    },
 });
}
	  }
 function AddUserMsg(text){
	 
	 $( ".Add_User_Msg" ).text( text )
				.addClass( "ui-state-highlight" );
			setTimeout(function() {
				$( "#Add_User_Msg" ).removeClass( "ui-state-highlight", 1500 );
			}, 500 );
	 }
 function Toalert(text){
	 alert(text);
	 }
	 
	 //初始化添加用户对话框
function initAddUserDialog(){
	
	$( "#User-form" ).dialog({
			autoOpen: false,
			height: 400,
			width: 350,
			modal: true,
			buttons: {
				"添加": function() {
					var type=$( "#Add_User_Type").autocomplete("option","selectedIndex");
					if(type==0){
			AddUserMsg("请选择正确的用户类型");
			return;
						}
					addUser($( "#Add_User_ID").val(),$( "#Add_User_Name").val(),$( "#Add_Login_Name").val(),$( "#Add_User_Pwd").val(),type,$( "#Add_User_UP").val(),$( "#Add_User_Addr").val(),$( "#Add_User_Tel").val());
				},
				//"取消": function() {
				//	$( this ).dialog( "close" );
				//}
			},
			"取消": function() {
				//allFields.val( "" ).removeClass( "ui-state-error" );
			}
		});
		$( "#DelectUser-form" ).dialog({
			autoOpen: false,
			height: 400,
			width: 350,
			modal: true,
			buttons: {
				"确认删除": function() {
				}
			},
			"取消": function() {
				//allFields.val( "" ).removeClass( "ui-state-error" );
			}
		});
	
	$( "#ModifyUserID-form" ).dialog({
			autoOpen: false,
			height: 400,
			width: 350,
			modal: true,
			buttons: {
				"修改": function() {
			ModifyUser($( "#Old_User_ID").val(),"ModifyUser_ID="+$( "#New_User_ID").val());
				},
				//"取消": function() {
				//	$( this ).dialog( "close" );
				//}
			},
			"取消": function() {
				//allFields.val( "" ).removeClass( "ui-state-error" );
			}
		});
}

//添加用户产品信息
function addUserProduct(User_ID,Product_ID,Price,Info){
	  	$.ajax({
   type: "POST",
   async: false,
   dataType: "xml",
   url: "../UserProductHandle/addUserProduct.jsp",
   data: encodeURI("User_ID="+User_ID+"&Product_ID="+Product_ID+"&Price="+Price+"&Info="+Info),
   success: function(xmlResponse){
    //getStart(xmlResponse);
	var statuc=$(xmlResponse).find("statuc").text();	
	if(statuc=="true"){
		AddUserMsg($(xmlResponse).find('msg').text());
		//$(jqgrid).trigger("reloadGrid");
		}else{
		AddUserMsg($(xmlResponse).find('msg').text());
		}
 	},
	error: function(XMLHttpRequest, textStatus, errorThrown) {
                        alert("status:"+XMLHttpRequest.status+"readyState:"+XMLHttpRequest.readyState+"text:"+textStatus);
                    },
 });
	}


//初始化添加用户产品价格对话框
function initAddUserProductDialog(){
				$( "#UserProduct-form" ).dialog({
			autoOpen: false,
			height: 400,
			width: 350,
			modal: true,
			buttons: {
				"添加": function() {
			addUserProduct($( "#Add_UserProduct_UserID").val(),$( "#Add_UserProduct_ProductID").val(),$( "#Add_UserProduct_Price").val(),$( "#Add_UserProduct_Info").val())
				},
				//"取消": function() {
				//	$( this ).dialog( "close" );
				//}
			},
			"取消": function() {
				//allFields.val( "" ).removeClass( "ui-state-error" );
			}
		});
	}
function initUserTypeAutocomplete(){
		$( "#Add_User_Type" ).autocomplete({
			source: "../userHandle/queryUser_Type.jsp",
			minLength: 0,
			selectedIndex:0,
			select: function( event, ui ) {
				//log( ui.item ?
				//	"Selected: " + ui.item.value + " aka " + ui.item.id :
				//	"Nothing selected, input was " + this.value );
				$(this).autocomplete({
				selectedIndex:ui.item.id,
					 });
			}
		});
		
		$( "#Add_User_UP" ).autocomplete({
		//source: "../userHandle/queryUser_Type.jsp",
			minLength: 0,
			selectedIndex:0,
			 source: function (request, response) {            
			 request.page = "1";  
			 request.rows= "100"; 
			 request.User_ID=encodeURIComponent(request.term);
				$.ajax({
					url: "../userHandle/searchUser.jsp?User_Type=2",
					data: request,
					dataType: "json",
					success: function( data, status ) {
					
							response( data );
						
					},
					error: function() {
					
							response( [] );
						
					}
				});
			 },
			select: function( event, ui ) {
				//log( ui.item ?
				//	"Selected: " + ui.item.value + " aka " + ui.item.id :
				//	"Nothing selected, input was " + this.value );
				//alert(ui.item.id)
			}
		});
		
		$( "#usertype" ).autocomplete({
			//source: "../userHandle/queryUser_Type.jsp",
			minLength: 0,
			selectedIndex:0,
			 source: function (request, response) {            
			 request.page = "1";  
			 request.rows= "100"; 
			 request.Product_Name=request.term;
				$.ajax({
					url: "../userHandle/queryUser_Type.jsp",
					data: request,
					dataType: "json",
					success: function( data, status ) {
					
							response( data );
						
					},
					error: function() {
					
							response( [] );
						
					}
				});
			 },
			select: function( event, ui ) {
				//log( ui.item ?
				//	"Selected: " + ui.item.value + " aka " + ui.item.id :
				//	"Nothing selected, input was " + this.value );
				//alert(ui.item.id);
				$(this).autocomplete({
									 selectedIndex:ui.item.id,
									 });
				 findUser();
			}
		});
		
		$( "#userid" ).autocomplete({
		//source: "../userHandle/queryUser_Type.jsp",
			minLength: 0,
			selectedIndex:0,
			 source: function (request, response) {            
			 request.page = "1";  
			 request.rows= "100"; 
			 request.User_ID=encodeURIComponent(request.term);
				$.ajax({
					url: "../userHandle/searchUser.jsp",
					data: request,
					dataType: "json",
					success: function( data, status ) {
					
							response( data );
						
					},
					error: function() {
					
							response( [] );
						
					}
				});
			 },
			select: function( event, ui ) {
				//log( ui.item ?
				//	"Selected: " + ui.item.value + " aka " + ui.item.id :
				//	"Nothing selected, input was " + this.value );
				//alert(ui.item.id)
			}
		});
		
				$( "#username" ).autocomplete({
		//source: "../userHandle/queryUser_Type.jsp",
			minLength: 0,
			selectedIndex:0,
			 source: function (request, response) {            
			 request.page = "1";  
			 request.rows= "100"; 
			 request.User_Name=encodeURIComponent(request.term);
				$.ajax({
					url: "../userHandle/searchUser_Name.jsp",
					data: request,
					dataType: "json",
					success: function( data, status ) {
					
							response( data );
						
					},
					error: function() {
					
							response( [] );
						
					}
				});
			 },
			select: function( event, ui ) {
				//log( ui.item ?
				//	"Selected: " + ui.item.value + " aka " + ui.item.id :
				//	"Nothing selected, input was " + this.value );
				//alert(ui.item.id)
			}
		});
		
		$( "#Add_UserProduct_UserID" ).autocomplete({
			//source: "../userHandle/queryUser_Type.jsp",
			minLength: 0,
			selectedIndex:0,
			 source: function (request, response) {            
			 request.page = "1";  
			 request.rows= "100"; 
			 request.User_ID=encodeURIComponent(request.term);
				$.ajax({
					url: "../userHandle/searchUser.jsp?User_Type=3",
					data: request,
					dataType: "json",
					success: function( data, status ) {
					
							response( data );
						
					},
					error: function() {
					
							response( [] );
						
					}
				});
			 },
			select: function( event, ui ) {
				//log( ui.item ?
				//	"Selected: " + ui.item.value + " aka " + ui.item.id :
				//	"Nothing selected, input was " + this.value );
				//alert(ui.item.id)
			}
		});
				$( "#Add_UserProduct_ProductID" ).autocomplete({
			//source: "../userHandle/queryUser_Type.jsp",
			 minLength: 0,
			selectedIndex:0,
			 source: function (request, response) {            
			 request.page = "1";  
			 request.rows= "100"; 
			 request.Product_Name=encodeURIComponent(request.term);
				$.ajax({
					url: "../productHandle/searchProduct.jsp",
					data: request,
					dataType: "json",
					success: function( data, status ) {
					
							response( data );
						
					},
					error: function() {
					
							response( [] );
						
					}
				});
			 },
			select: function( event, ui ) {
				//log( ui.item ?
				//	"Selected: " + ui.item.value + " aka " + ui.item.id :
				//	"Nothing selected, input was " + this.value );
			
			}
		});
	}
function initfindUser(){
			$("#find").click(
		    function(){
	 findUser();
			}
		);
	}
	function findUser(){
		/*获取select 选中的 text : 
	$("#ddlRegType").find("option:selected").text(); 
	获取select选中的 value: 
	$("#ddlRegType ").val(); 
	获取select选中的索引: 
	$("#ddlRegType ").get(0).selectedIndex; 
	设置select: 
	设置select 选中的索引： 
	$("#ddlRegType ").get(0).selectedIndex=index;//index为索引值*/
	//alert("userid="+$( "#userid").val()+"  username="+$( "#username").val()+"  usertype="+$( 			"#usertype").get(0).selectedIndex);
var userid=encodeURIComponent($( "#userid").val());
var username=encodeURIComponent($( "#username").val());
var usertype=$("#usertype").autocomplete("option","selectedIndex");
$("#User_list1").jqGrid('setGridParam',{ url: '../userHandle/queryUser.jsp',
postData:{User_ID:userid,User_Name:username,User_Type:usertype}
}).trigger('reloadGrid'); 
		}
		
		
		function checkLength(o, n, min, max ) {
			if ( o.val().length > max || o.val().length < min ) {
				o.addClass( "ui-state-error" );
				AddUserMsg(n + " 长度必须在" +
					min + "和 " + max + "区间." );
				return false;
			} else {
				return true;
			}
		}

		function checkRegexp( o, regexp, n ) {
			if ( !( regexp.test( o.val() ) ) ) {
				o.addClass( "ui-state-error" );
				AddUserMsg( n );
				return false;
			} else {
				return true;
			}
		}
// JavaScript Document